package com.pengtu.web.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.Constants;
import com.pengtu.dao.HibernateUtils;
import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.dao.QueryFilter.MatchType;
import com.pengtu.entity.app.ExternalOrganization;
import com.pengtu.entity.app.InsideOrganization;
import com.pengtu.entity.app.Organization;
import com.pengtu.entity.app.Role;
import com.pengtu.entity.app.User;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.service.ServiceException;
import com.pengtu.service.app.AccountManager;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 * 
 * @author calvin
 */
// 定义URL映射对应/account/user.action
@Namespace("/account")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({
		@Result(name = BaseActionSupport.RELOAD, location = "user.action", type = "redirect"),
		@Result(name = "homepage", location = "role.action", type = "redirect"),
		@Result(name = "insideUser", location = "/account/user!findinsideUser.action", type = "redirect"),
		@Result(name = "outUser", location = "/account/user!findoutUser.action", type = "redirect") })
public class UserAction extends BaseActionSupport<User> {

	private static final long serialVersionUID = 8683878162525847072L;

	private AccountManager accountManager;

	// -- 页面属性 --//
	private String id;
	private User entity;
	private List<User> allUserList;
	private Page<User> page = new Page<User>(10);// 每页5条记录
	private List<String> checkedRoleIds; // 页面中钩选的角色id列表
	private Organization org;
	private List<InsideOrganization> insideorganizationList = new ArrayList<InsideOrganization>();
	private List<ExternalOrganization> exterorganizationList = new ArrayList<ExternalOrganization>();

	public String info() throws Exception {
		User user = SpringSecurityUtils.getCurrentUser();
		User myinfo = accountManager.getUser(user.getId());
		Struts2Utils.getRequest().setAttribute("user", myinfo);
		return Constants.INFO;
	}

	public String complete() throws Exception {
		return Constants.COMPLETE;
	}

	// -- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		// 设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.DESC);
		}
		page = accountManager.findPageUser(page, queryfilter);
		return SUCCESS;
	}

	@Action("/account/api/user")
	public String apilist() throws Exception {
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.DESC);
		}
		page = accountManager.findPageUser(page, queryfilter);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {

		checkedRoleIds = entity.getRoleIds();
		String label = Struts2Utils.getParameter("label");
		if ("out".equals(label)) {
			// 加载外部用户列表
			return "outupdate";
		}
		if (StringUtils.isNotEmpty(id)) {
			org = entity.getOrganization();
		}
		// 加载内部用户列表
		insideorganizationList = accountManager.getInsideOrganization();
		if ("inside".equals(label))
			return "insideupdate";
		return INPUT;
	}

	public String view() throws Exception {
		if (StringUtils.isEmpty(id)) {
			entity = new User();
		} else {
			entity = accountManager.getUser(id);
			checkedRoleIds = entity.getRoleIds();
		}
		return VIEW;
	}

	/**
	 * 
	 * prepareLoadInfo: 适用:修改前加载数据
	 * 
	 * @exception
	 * @since 1.0.0
	 */
	public void prepareLoadInfo() {
		String userName = SpringSecurityUtils.getCurrentUserName();
		entity = accountManager.findUserByLoginName(userName);
	}

	public String loadInfo() {
		return "update";
	}

	/**
	 * 
	 * convertUser: 适用:存储用户账户属性
	 * 
	 * @exception
	 * @since 1.0.0
	 */
	public void convertUser() {
		// 如果未选中 锁定 ,账户过期 ,密码过期 ,设置默认值为0
		if ("false".equals(entity.getEnable()))
			entity.setEnable("0");
		if ("false".equals(entity.getExpired()))
			entity.setExpired("0");
		if ("false".equals(entity.getCredexpired()))
			entity.setCredexpired("0");
		if ("false".equals(entity.getLocked()))
			entity.setLocked("0");
	}

	@Override
	public String save() throws Exception {
		org = accountManager.getOrganization(org.getId());
		if (null != org)
			entity.setOrganization(org);
		// 根据页面上的checkbox选择 整合User的Roles Set
		HibernateUtils.mergeByCheckedIds(entity.getRoleList(), checkedRoleIds,
				Role.class);
		convertUser();
		accountManager.saveUser(entity);
		addActionMessage("保存用户成功");
		return "insideUser";
	}

	/**
	 * 
	 * prepareSaveUpdate: 适用:修改当前用户信息
	 * 
	 * @exception
	 * @since 1.0.0
	 */
	public void prepareSaveUpdate() {
		String userName = SpringSecurityUtils.getCurrentUserName();
		entity = accountManager.findUserByLoginName(userName);
	}

	public String saveUpdate() {
		// 根据页面上的checkbox选择 整合User的Roles Set
		HibernateUtils.mergeByCheckedIds(entity.getRoleList(), checkedRoleIds,
				Role.class);
		accountManager.saveUser(entity);
		addActionMessage("修改用户" + entity.getUsername());
		return "update";
	}

	/**
	 * 
	 * prepareSaveUpdate: 适用:保存或修改内部用户信息
	 * 
	 * @throws Exception
	 * 
	 * @exception
	 * @since 1.0.0
	 */
	public void prepareSaveInsideUser() throws Exception {
		prepareModel();
	}

	public String saveInsideUser() {
		//
		// if(null!=org){
		// if (!entity.getOrganization().getId().equals(org.getId())) {
		// QueryFilter queryfilter = QueryFilter
		// .buildFromHttpRequest(Struts2Utils.getRequest());
		// queryfilter.addFilter("user.id", entity.getId());
		// Page<UserDepartment> page = new Page<UserDepartment>(10);
		// if (!page.isOrderBySetted()) {
		// page.order(Page.DESC);
		// page.orderBy("createDate");
		// }
		// page = accountManager.searchUserDepartment(page, queryfilter);
		// List<UserDepartment> userdeptList = page.getResult();
		// if (userdeptList.size() != 0) {
		// UserDepartment userDept = userdeptList.get(0);
		// userDept.getDepartment();
		// userDept.setEndDate(new Date());
		// accountManager.save(userDept);
		// }
		// }
		// }
		convertUser();
		org = accountManager.getOrganization(org.getId());
		entity.setOrganization(org);

		// 根据页面上的checkbox选择 整合User的Roles Set
		HibernateUtils.mergeByCheckedIds(entity.getRoleList(), checkedRoleIds,
				Role.class);
		accountManager.saveUser(entity);
		if ("".equals(entity.getId()) || null == entity.getId()) {
			addActionMessage("保存用户" + entity.getUsername());
		} else {
			addActionMessage("修改用户" + entity.getUsername());
		}
		return "insideUser";
	}

	/**
	 * 
	 * prepareSaveUpdate: 适用:修改外部用户信息
	 * 
	 * @throws Exception
	 * 
	 * @exception
	 * @since 1.0.0
	 */
	public void prepareUpdateUser() throws Exception {
		prepareModel();
	}

	public String updateUser() {
		/*
		 * if(!entity.getOrganization().getId().equals(org.getId())){
		 * QueryFilter queryfilter =
		 * QueryFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		 * queryfilter.addFilter("user.id",entity.getId()); Page
		 * <UserDepartment> page = new Page<UserDepartment>(10);
		 * if(!page.isOrderBySetted()){ page.order(Page.DESC);
		 * page.orderBy("createDate"); } page =
		 * accountManager.searchUserDepartment(page, queryfilter);
		 * List<UserDepartment> userdeptList = page.getResult();
		 * if(userdeptList.size()!=0){ UserDepartment userDept =
		 * userdeptList.get(0); userDept.setEndDate(new Date());
		 * accountManager.save(userDept); } } entity.setOrganization(org);
		 */
		// 根据页面上的checkbox选择 整合User的Roles Set
		HibernateUtils.mergeByCheckedIds(entity.getRoleList(), checkedRoleIds,
				Role.class);
		accountManager.saveUser(entity);
		addActionMessage("修改用户" + entity.getUsername());
		return "outUser";
	}

	/**
	 * 
	 * checkPass: 适用:检查旧密码是否输入正确
	 * 
	 * @exception
	 * @since 1.0.0
	 */
	public void checkPass() {
		String userName = SpringSecurityUtils.getCurrentUserName();
		User userInfo = accountManager.findUserByLoginName(userName);
		if (null != userInfo) {
			String oldpass = Struts2Utils.getParameter("oldpass");
			if (userInfo.getPassword().equals(oldpass)) {
				Struts2Utils.renderText("true");
			} else {
				Struts2Utils.renderText("false");
			}
		}
	}

	/**
	 * 
	 * updatepass: 适用:修改密码
	 * 
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	public String updatepass() {
		String userName = SpringSecurityUtils.getCurrentUserName();
		User userInfo = accountManager.findUserByLoginName(userName);
		if (null != userInfo) {
			String oldpass = Struts2Utils.getParameter("oldpass");
			String newpass = Struts2Utils.getParameter("newpass");
			if (userInfo.getPassword().equals(oldpass)) {
				userInfo.setPassword(newpass);
				accountManager.saveUser(userInfo);
			}
		}
		return "homepage";
	}

	@Override
	public String delete() throws Exception {
		try {
			accountManager.deleteUser(id);
			addActionMessage("删除用户成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage("删除用户失败");
		}
		String label = Struts2Utils.getParameter("label");

		if ("inside".equals(label)) {
			return "insideUser";
		} else if ("out".equals(label)) {
			return "outUser";
		}
		return RELOAD;
	}

	// -- 其他Action函数 --//
	/**
	 * 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkLoginName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String newLoginName = request.getParameter("userName");
		String oldLoginName = request.getParameter("oldLoginName");

		if (accountManager.isLoginNameUnique(newLoginName, oldLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	/**
	 * 注册 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkregisterEmail() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String newEmail = request.getParameter("email");
		String oldEmail = request.getParameter("oldEmail");

		if (accountManager.isregisterEmailUnique(newEmail, oldEmail)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	/**
	 * 根据单位ID查询外部人员
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchForChoose() throws Exception {
		String orgId = Struts2Utils.getParameter("orgId");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<User> users = null;
		if (StringUtils.isNotEmpty(orgId)) {
			users = accountManager.findUsersByOrgId(orgId);
			for (User user : users) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", user.getId());
				map.put("userName", user.getUserName());
				map.put("name", user.getName());
				map.put("email", user.getEmail());
				map.put("mobilePhone", user.getMobilePhone());
				list.add(map);
			}
		}
		Struts2Utils.renderJsontoExtTotalResults(list);
		return NONE;
	}

	/**
	 * 根据部门ID查询内部人员
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchChooseByDepId() throws Exception {
		String orgId = Struts2Utils.getParameter("orgId");
		String depId = "";
		if (StringUtils.isNotEmpty(orgId)) {
			if (orgId.indexOf("_") != -1) {
				depId = orgId.substring(0, orgId.indexOf("_"));
			}
		}
		List<User> users = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (StringUtils.isEmpty(depId)) {
			QueryFilter queryfilter = QueryFilter
					.buildFromHttpRequest(Struts2Utils.getRequest());
			queryfilter.addFilter("organization.id", orgId);
			queryfilter.addFilter("organization.type", "0");
			users = accountManager.searchUser(queryfilter);
		} else {
			users = accountManager.searchUserByDepId(depId);
		}
		for (User user : users) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", user.getId());
			map.put("userName", user.getUserName());
			map.put("name", user.getName());
			map.put("mobilePhone", user.getMobilePhone());
			map.put("sex", user.getSex());
			map.put("email", user.getEmail());
			list.add(map);
		}
		Struts2Utils.renderJsontoExtTotalResults(list);
		return null;

	}

	/**
	 * 根据角色ID查询同一角色的用户
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchChooseByRole() throws Exception {
		String roleId = Struts2Utils.getParameter("roleId");
		List<User> users = null;
		users = accountManager.searchRoleUser(roleId);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (User user : users) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", user.getId());
			map.put("userName", user.getUserName());
			map.put("name", user.getName());
			map.put("mobilePhone", user.getMobilePhone());
			map.put("sex", user.getSex());
			map.put("email", user.getEmail());
			list.add(map);
		}
		Struts2Utils.renderJsontoExtTotalResults(list);
		return null;

	}
	
	
	/**
	 * 根据角色ID查询同一角色的用户
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchChooseByUserName() throws Exception {
		
		QueryFilter queryuserName =QueryFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		queryuserName.addFilter("organization.type","0");
		List<User> users = null;
		users = accountManager.searchUser(queryuserName);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (User user : users) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", user.getId());
			map.put("userName", user.getUserName());
			map.put("name", user.getName());
			map.put("mobilePhone", user.getMobilePhone());
			map.put("sex", user.getSex());
			map.put("email", user.getEmail());
			list.add(map);
		}
		Struts2Utils.renderJsontoExtTotalResults(list);
		return null;

	}


	/**
	 * 
	 * findoutUser: 适用:查找内部单位列表
	 * 
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	public String findinsideUser() {

		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		queryfilter.addFilter("organization.type", "0");
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = accountManager.findInsideUser(page, queryfilter);
		return "inside";

	}

	/**
	 * 
	 * findoutUser: 适用:查找外部单位列表
	 * 
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	public String findoutUser() {

		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		queryfilter.addFilter("organization.type", "0", MatchType.NE);
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = accountManager.findOutUser(page, queryfilter);
		return "out";
	}

	@Override
	protected void prepareModel() throws Exception {

		if (StringUtils.isNotEmpty(id)) {
			entity = accountManager.getUser(id);
		} else {
			entity = new User();
		}
	}

	// -- 页面属性访问函数 --//
	/**
	 * list页面显示用户分页列表.
	 */
	public Page<User> getPage() {
		return page;
	}

	/**
	 * input页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return accountManager.getAllRole();
	}

	/**
	 * input页面显示用户拥有的角色.
	 */
	public List<String> getCheckedRoleIds() {
		return checkedRoleIds;
	}

	/**
	 * input页面提交用户拥有的角色.
	 */
	public void setCheckedRoleIds(List<String> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	public List<InsideOrganization> getInsideorganizationList() {
		return insideorganizationList;
	}

	public void setOrg(Organization org) {
		this.org = org;
	}

	public Organization getOrg() {
		return org;
	}

	public List<ExternalOrganization> getExterorganizationList() {
		return exterorganizationList;
	}

	// -- ModelDriven 与 Preparable函数 --//
	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public User getModel() {
		return entity;
	}

	public List<User> getAllUserList() {
		return allUserList;
	}

}
